package servlets;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.ejb.EJB;
import javax.mail.Authenticator;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import javax.jms.*;
import javax.mail.MessagingException;
import javax.mail.Transport;

import service.CandidateService;
import service.PositionService;
import service.UserService;
import entityJPA.Candidate;
import entityJPA.Position;
import entityJPA.User;

/**
 * Servlet implementation class CandidateServlet
 */
@WebServlet("/CandidateServlet")
@MultipartConfig(maxFileSize = 16177215)
public class CandidateServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private PrintWriter out;
	@EJB
	private CandidateService candService;
	@EJB
	private PositionService posService;

	@EJB
	private UserService usrService;

	private InputStream inputStream = null;
	
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public CandidateServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession h=request.getSession();
		h.setAttribute("operationIsSuccesful", "no");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		HttpSession h=request.getSession();
		h.setAttribute("operationIsSuccesful", "no");
		if (request.getParameter("add") != null) {
			addCandidate(request, response);
		} else if (request.getParameter("edit") != null) {
			editCandidate(request, response);
		} else if (request.getParameter("delete") != null) {
			deleteCandidate(request, response);
		} else if (request.getParameter("hire") != null) {
			try {
				hireCandidate(request, response);
			} catch (Exception e) {
				h.setAttribute("exceptionMessage",
						"Error occured while trying to hire the candidate.");
				response.sendRedirect("/jt-hr-WEB/SharedPages/ExceptionHandler.jsp");
			}
		}

	}

	private void addCandidate(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		PrintWriter out = response.getWriter();
		try {
			Candidate candidate = new Candidate();

			Part filePart = request.getPart("cv");
			inputStream = filePart.getInputStream();
			if (filePart.getSize() != 0) {
				candidate.setCvUpload(getBytes(inputStream));
			}

			candidate.setFirstName(request.getParameter("firstName"));
			candidate.setLastName(request.getParameter("lastName"));
			candidate.setAddress(request.getParameter("address"));
			candidate.setCellNumber(request.getParameter("cellNumber"));
			candidate.setEmail(request.getParameter("e-mail"));
			candidate.setHomeNumber(request.getParameter("homeNumber"));
			if (request.getParameter("relocation") != null)
				candidate.setRelocation(true);
			else {
				candidate.setRelocation(false);
			}

			int id = Integer.parseInt(request.getParameter("position"));
			out.println(id);
			Position position = posService.getPositionById(id);
			candidate.setPosition(position);
			candService.addCandidate(candidate);
			int uId = position.getIdUser();
			User u = usrService.getUserById(uId);
			sendMail(u.getEmail(), position, candidate);
			HttpSession h=request.getSession();
			h.setAttribute("operationIsSuccesful", "yes");
			request.getRequestDispatcher("displayCandidate").forward(request,response);

		} catch (Exception e) {
			HttpSession h = request.getSession();
			h.setAttribute("exceptionMessage",
					"Database error. Please make sure the submited data is correct and try again.");
			response.sendRedirect("/jt-hr-WEB/SharedPages/ExceptionHandler.jsp");
		}

	}

	private void deleteCandidate(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Candidate cand = new Candidate();
		cand.setIdCandidate(Integer.parseInt(request.getParameter("id")));
		try {
			candService.removeCandidate(cand);
			HttpSession h=request.getSession();
			h.setAttribute("operationIsSuccesful", "yes");
			request.getRequestDispatcher("displayCandidate").forward(request,response);

		} catch (Exception e) {
			HttpSession h = request.getSession();
			h.setAttribute("exceptionMessage",
					"Database error. Please make sure the submited data is correct and try again.");
			response.sendRedirect("/jt-hr-WEB/SharedPages/ExceptionHandler.jsp");
		}
	}

	private void editCandidate(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Candidate candidate = new Candidate();
		out = response.getWriter();
		try {
			candidate.setIdCandidate(Integer.parseInt(request
					.getParameter("id")));

			Part filePart = request.getPart("cv");
			inputStream = filePart.getInputStream();
			if (filePart.getSize() != 0) {
				candidate.setCvUpload(getBytes(inputStream));
			} else {
				candidate.setCvUpload(candService.getCandidateById(
						candidate.getIdCandidate()).getCvUpload());
			}
			candidate.setFirstName(request.getParameter("firstName"));
			candidate.setLastName(request.getParameter("lastName"));
			candidate.setAddress(request.getParameter("address"));
			candidate.setEmail(request.getParameter("e-mail"));
			candidate.setCellNumber(request.getParameter("cellNumber"));

			int id = Integer.parseInt(request.getParameter("position"));
			Position position = posService.getPositionById(id);
			candidate.setPosition(position);
			candService.editCandidate(candidate);
			HttpSession h=request.getSession();
			h.setAttribute("operationIsSuccesful", "yes");
			request.getRequestDispatcher("displayCandidate").forward(request,response);

		} catch (Exception e) {
			HttpSession h = request.getSession();
			h.setAttribute("exceptionMessage",
					"Database error. Please make sure the submited data is correct and try again.");
			response.sendRedirect("/jt-hr-WEB/SharedPages/ExceptionHandler.jsp");
		}
	}

	private void hireCandidate(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException,
			Exception {
		out = response.getWriter();
		try {
			Candidate candidate = candService.getCandidateById(Integer
					.parseInt(request.getParameter("id")));
			if (candidate.getPosition().getPositionstatus().getValue()
					.equalsIgnoreCase("active")) {
				candidate.setAccepted(true);
				candService.editCandidate(candidate);
				posService.decrementNumberOfPersons(candidate.getPosition());
			} 
			HttpSession h=request.getSession();
			h.setAttribute("operationIsSuccesful", "yes");
			request.getRequestDispatcher("displayCandidate").forward(request,
					response);

		} catch (Exception e) {
			HttpSession h = request.getSession();
			h.setAttribute("exceptionMessage",
					"Database error. Please make sure the submited data is correct and try again.");
			response.sendRedirect("/jt-hr-WEB/SharedPages/ExceptionHandler.jsp");
		}
	}

	public static byte[] getBytes(InputStream is) throws IOException {

		int len = 0;
		int size = 1024;
		byte[] buf;

		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		buf = new byte[size];
		while ((len = is.read(buf, 0, size)) != -1)
			bos.write(buf, 0, len);
		buf = bos.toByteArray();

		return buf;
	}

	public void sendMail(String to, Position p, Candidate c) {

		String smtpServer = "smtp.gmail.com";
		String from = "javatrainingmsg@gmail.com";
		String subject = "Notification";
		String bodyS = "Dear User, a candiate has been added on Position "
				+ p.getName() + " ,name of the" + "candidate is "
				+ c.getLastName() + " " + c.getFirstName();

		Properties props = new Properties();

		props.put("mail.smtp.ssl.trust", "zmr.msg.de");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.host", "zmr.msg.de");
		props.put("mail.smtp.port", "25");
		Authenticator auth = new SMTPAuthenticator();
		javax.mail.Session session = javax.mail.Session
				.getInstance(props, auth);
		javax.mail.Message msg1 = new MimeMessage(session);
		try {
			InternetAddress addressFrom = new InternetAddress(from);
		} catch (AddressException ex) {
			Logger.getLogger(Message.class.getName()).log(Level.SEVERE, null,
					ex);
		}
		try {
			msg1.setFrom(new InternetAddress(from));
			msg1.setRecipients(javax.mail.Message.RecipientType.TO,
					InternetAddress.parse(to, false));
			msg1.setSubject(subject);
			msg1.setContent(bodyS, "text/plain");
			Transport.send(msg1);
			// Thread.sleep(10000);

		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
